package org.xukai.common.util.compress;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
public class RSAUtils {

	private final static String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";

	private final static String CHARSET_ENCODING = "UTF-8";

	private static final KeyPair keyPair = initKey();

	private static KeyPair initKey() {
		try {
			Provider provider =new org.bouncycastle.jce.provider.BouncyCastleProvider();
			Security.addProvider(provider);
			SecureRandom random = new SecureRandom();
			KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);
			generator.initialize(1024, random);
			return generator.generateKeyPair();
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String generateBase64PublicKey() {
		PublicKey publicKey = keyPair.getPublic();
		return new String(Base64.encodeBase64(publicKey.getEncoded()));
	}

	public static String decryptBase64(String string) {
		return new String(decrypt(Base64.decodeBase64(string.getBytes())));
	}

	private static byte[] decrypt(byte[] byteArray) {
		try {
			Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
			Security.addProvider(provider);
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, provider);
			PrivateKey privateKey = keyPair.getPrivate();
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			return cipher.doFinal(byteArray);
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}


	/**
	 * 加密
	 * @param plainText
	 * @return
	 */
	public static String encrypt(String plainText) {
		try {
			PublicKey key = keyPair.getPublic();
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return new String(Base64.encodeBase64(cipher.doFinal(plainText.getBytes
					(CHARSET_ENCODING))));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
